package controllers

import (
	"du/database"
	"du/models"
	"du/repositories"
	"du/services"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

type UserController struct {
	userService *services.UserService
}

type User struct {
	Name  string
	Email string
}

func NewUserController() *UserController {
	userRepo := repositories.NewUserRepository()
	userService := services.NewUserService(userRepo)

	return &UserController{
		userService: userService,
	}
}

func (uc *UserController) GetUser(ctx *gin.Context) {
	user, err := uc.userService.GetUser()

	if err != nil {
		ctx.JSON(http.StatusInternalServerError, []gin.H{})
		return
	}

	ctx.JSON(200, user)
}

func (uc *UserController) CreateUser(ctx *gin.Context) {
	var user User

	if err := ctx.ShouldBindJSON(&user); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"err": err.Error(),
		})
		return
	}

	record := &models.User{
		Name:     user.Name,
		Email:    user.Email,
		Password: "123",
	}

	if database.RedisClient.Incr(ctx, "").Val() > 1 {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"err": "repeat",
		})
		return
	}

	err := uc.userService.CreateUser(record)

	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	ctx.JSON(200, record)
}

func (uc *UserController) GetByID(ctx *gin.Context) {
	idStr := ctx.Param("id")
	// 解析ID并转为uint类型

	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		// 解析出错，处理错误
	}

	uintID := uint(id)

	user, err := uc.userService.GetUserByID(uintID)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 返回用户信息
	ctx.JSON(200, user)
}
